/**
 * Created by Administrator on 2016/12/16 0016.
 */
//全局变量
var globalConfig={
    ajaxarr:[],
    serverPath:window.location.protocol + '//' + window.location.host+"/svr/",
    fullDialog:[],
};
//本地存储相关方法
function _setStorage(key,val){
    localStorage.setItem(key,val);
}
function _getStorage(key){
    return localStorage.getItem(key);
}
function _clearStorage(){
    localStorage.clear();
}
function _removeStorage(key){
    localStorage.removeItem(key);
}

//Ajax方法
function callSvr(urlPath,data,success,err){
    if($.inArray(urlPath,globalConfig.ajaxarr)>-1)return false;
    globalConfig.ajaxarr.push(urlPath);
    $.ajax({
        cache:false,
        async:true,
        type : 'POST',
        url : globalConfig.serverPath+urlPath,
        data : data,
        dataType : 'json',
        success:function(ret){
            if(ret.err==-9 || ret.err==10){//session失效
                alert("身份失效,请重新登录");
                window.location.href="/login.html"
            }else{
                if(_judgeType(success,'function'))success(ret);
            }
        },
        error:function(){
            alert("网络错误,请稍后重试");
            if(_judgeType(err,'function'))err();
        },
        complete:function(){
            $.each(globalConfig.ajaxarr,function(i,v){
                if(v==urlPath){
                    globalConfig["ajaxarr"].splice(i,1);
                    return;
                }
            })
        }
    })
}
//表格方法
$.fn.getGrid = function(opts) {
    var $self=$(this);
    var pagingation = "<div class='col-xs-12 text-center'>" +
        "<ul class='pagination' style='margin-right:10px;'>" +
        "<li><a>共 {{count}} 行 {{pageTotal}} 页，当前第 {{page}} 页</a></li></ul>"+
        "<ul class='pagination' style='margin-right:5px' id='fPaging'>"+
        "<li class='{{if page==1}}active{{/if}} start'><a class='btn btn-info'>首页</a></li>"+
        "<li class='{{if page==1}}disabled{{/if}} up'><a class='btn btn-info'>上一页</a></li>"+
        "<li class='{{if page==pageTotal}}disabled{{/if}} down'><a class='btn btn-info'>下一页</a></li>"+
        "<li class='{{if page==pageTotal}}active{{/if}} total'><a class='btn btn-info'>末页</a></li></ul>"+
        "{{if dataExport}}<ul class='pagination' style='margin-right:5px'>"+
        "<li><a id='dataExport' class='btn btn-info'>导出</a></li></ul>{{/if}}</div>";
    var settings={
        tpl:'',
        sql:'',
        startIndex:0,
        limit:10,
        page:1,
        orgId:1,
        dataExport:true,
    };
    settings=$.extend(settings, opts);
    settings.limit=Math.floor((this.height()-115)/33);
    callSvr("Report/getDataGrid",settings,function(res){
        settings.count = res.count;
        settings.pageTotal = Math.ceil(settings.count / settings.limit);
        //if(res.list.length==0){
        //    $(self).html("没有数据");
        //    return false;
        //}
        var tpl = template(settings.tpl, res);
        var render = template.compile(pagingation);
        tpl += render(settings);
        $self.html(tpl);
        $("#fPaging").delegate("li","click",function(){
            if($(this).hasClass("disabled"))return false;
            if($(this).hasClass("start")){
                settings.startIndex=0;
                settings.page=1;
            }else if($(this).hasClass("up")){
                settings.page--;
                settings.startIndex=(settings.page-1)*settings.limit;
            }else if($(this).hasClass("down")){
                settings.page++;
                settings.startIndex=(settings.page-1)*settings.limit;
            }else if($(this).hasClass("total")){
                settings.page=settings.pageTotal;
                settings.startIndex=(settings.pageTotal-1)*settings.limit;
            }
            $self.getGrid(settings);
        });
    },true)
};
//生成组织树
function _getOrgTree(divId,callback,execute){
    var $tree=$("#"+divId);
    var child={};
    var $toggle="<a class='open-org-btn'><i class='fa fa-right'></i></a>";
    var list_tpl="<li class='em-list-cell {{if node==1}}open checked-org{{/if}}' title='{{name}}'>"+
        "<div class='area' id='org{{orgId}}'>"+
        "<a class='org-item' data-orgid='{{orgId}}' data-name='{{name}}'>"+ "" +
        "<span style='padding-left:5px'>{{name}}</span></a></div></li>"+
        "<ul class='em-list' id='child{{orgId}}'></ul>";
    var render = template.compile(list_tpl);
    var init=function(ret){
        if(!globalConfig["orgtree"])globalConfig["orgtree"]=ret;
        for(var i=0;i<ret.length;i++){
            $li=$(render(ret[i]));
            if(ret[i].node==1){
                $li.appendTo($tree);
            }else{
                var pid=ret[i].pid;
                if(child[pid]){
                    $li.appendTo(child[pid]);
                }else{
                    child[pid]=$("#child"+ret[i].pid);
                    $li.appendTo(child[pid]);
                    $("#org"+pid).prepend($toggle);
                }
            }
        }
        $(".open-org-btn").on("click",function(){
            var $foo=$(this).parents(".em-list-cell");
            if($foo.hasClass("open")){
                $foo.removeClass("open");
            }else{
                $foo.addClass("open")
            }
        });
        $(".org-item").on("click", function(){
            $(".checked-org").removeClass("checked-org");
            $(this).parents(".em-list-cell").addClass("checked-org");
            callback($(this).data("orgid"),$(this).data("name"));
        });
        if(execute)$(".org-item:first").click();
    }
    if(globalConfig["orgtree"]){
        init(globalConfig["orgtree"])
    }else{
        callSvr("OrgManage/getOrgTreeByPid",{},init,true);
    }
};
//将组织树区缩放
function toggleTree(treeId,tableId,el){
    var $tree=$("#"+treeId);
    var $table=$("#"+tableId);
    if($tree.hasClass("col-xs-2")){
        $(el).text("展开");
    }else{
        $(el).text("隐藏");
    }
    $tree.toggleClass("col-xs-2 col-xs-1");
    $table.toggleClass("col-xs-11 col-xs-10");
    $tree.find("ul").toggleClass("short");
}
//模态框
function _createDialog(opts) {
    var dialog_tpl = "<div class='em-dialog aui-flex-col aui-flex-center aui-flex-col' id='{{id}}'>" +
        "<div class='em-dialog-pack' style='height:{{height}};width:{{width}}'>"+
        "<div class='em-dialog-title'><span style='color:#ccc'>{{title}}</span><div class='pull-right'>"+
        "<i class='glyphicon glyphicon-remove em-dialog-remove'>" +
        "</i></div></div><div class='em-dialog-box' id='{{id}}-box'></div></div></div>"
    var setting = {
        id:'em-dialog',
        height:'60%',
        width:'20%',
        url:'',
        tpl:'',
        _callback:'',
        title:'弹出窗口'
    }
    setting = $.extend(setting, opts);
    var render=template.compile(dialog_tpl);
    var dialog=render(setting);
    $("body").append(dialog);
    var $dialog=$("#"+setting.id);
    if(setting.url)$dialog.find(".em-dialog-box").load(setting.url);
    if(setting.tpl)$dialog.find(".em-dialog-box").append(setting.tpl);
    $dialog.find(".em-dialog-remove").on("click",function(){
        $dialog.remove();
    })
    return{
        close:function(){
            $dialog.remove();
        }
    }
}
//生成导航菜单
function initNavMenu(){
    var root={};
    var $nav=$("#nav-head");
    var $navBody=$("#nav-body");
    var tpl="{{if PId==''}}<span class='nav-module'><p class='nav-title'>{{else}}<p class='nav-text'>{{/if}}{{if URL}}<a href='javascript:void(0)' class='nav-link nav_link' data-url='/page/{{URL}}'>{{Name}}</a>{{else}}{{Name}}{{/if}}</p>{{if PId==''}}</span>{{/if}}";
    var render=template.compile(tpl);
    callSvr("AccountManage/getNavData","",function(res){
        em.myId = res.AccountId;
        $("#user_info_btn").text(res.LoginName);
        var ml=res["MenuList"];
        for(var i=0;i<ml.length;i++){
            var mo=ml[i];
            var pid=mo.PId;
            var menuId=mo.MenuId;
            var menu=render(mo);
            var $menu=$(menu);
            if(pid==''){
                $menu.appendTo($nav)
                root[menuId]=$menu
            }else{
                $menu.appendTo(root[pid])
            }
        }
        for(o in root){
            if(!root[o].find("a").length)root[o].remove();
        }
        var height=$nav.height();
        $nav.hover(function(){
            $navBody.css("height",height);
        },function(){
            $navBody.css("height",50);
        })
        $(".nav_link").on("click",function(){
            $(".em-full-dialog").remove();
            globalConfig.fullDialog.splice(0,globalConfig.fullDialog.length);
            clearInt();
            var url=$(this).data("url");
            $navBody.css("height",50);
            _load(url);
        })
    })
};
/**load封装*/
function _load(url){
    $("#main").empty().load(url);
}
//表单处理相关方法
$.fn.formToJson_1 = function() {
    var values = {};
    this.find("*[name]").each(function() {
        if ($(this).prop("name")) {
            var val=this.value.trim();
            var eleName = $(this).prop("name");
            if (this.type == "checkbox") {
                if (this.checked) {
                    if (!values[eleName]) {
                        values[eleName] = val;
                    } else {
                        values[eleName]=values[eleName]+ "," + val;
                    }
                }
            } else {
                values[eleName]=val;
            }
        }
    });
    return values;
};
//满屏的dialog
function FullDialog(htmlUrl) {
    var id='full-'+htmlUrl.substring(htmlUrl.lastIndexOf("/")+1,htmlUrl.lastIndexOf("."));
    var zindex=$.inArray(id,globalConfig.fullDialog)
    if(zindex>-1){
        alert("请关闭当前窗口!再使用此功能");
        return false;
    }
    globalConfig.fullDialog.push(id);
    var $fd = $("<div id='"+id+"' class='em-full-dialog'></div>").appendTo("body");
    $fd.css("z-index",zindex+306).load(htmlUrl);
}
//关闭当前fullDialog
function colseFullDialog() {
    var $currFd=$(".em-full-dialog:last");
    var id=$currFd.prop("id");
    $.each(globalConfig.fullDialog,function(i,n){
        if(n==id){
            globalConfig['fullDialog'].splice(i,1);
            return;
        }
    });
    $currFd.remove();
    clearInt();
}
//清除延时器
function clearInt(){
    if(globalConfig.tjint){
        clearTimeout(globalConfig.tjint);
        delete globalConfig.tjint;
    }
}
function _judgeType(obj,type){
    if(type){
        var type=type.toLowerCase();
        return Object.prototype.toString.call(obj).toLowerCase()==='[object '+type+']';
    }else{
        return Object.prototype.toString.call(obj).toLowerCase()
    }

}
function _showProgress(){
    $('#mask').show();
}
function _hideProgress(){
    $('#mask').hide();
}
